package com.groupbaby.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.groupbaby.ydd.common.BusinessException;
import com.groupbaby.ydd.common.ResultData;
import com.groupbaby.ydd.dto.SysMenuDto;
import com.groupbaby.ydd.entity.SysMenu;
import com.groupbaby.ydd.entity.SysRoleMenu;
import com.groupbaby.ydd.mapper.SysMenuMapper;
import com.groupbaby.ydd.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {




    /**
     * 递归获取子菜单
     * @param sysMenu
     * @return
     */
    @Override
    public SysMenu getChildren(SysMenu sysMenu){

        //查询出传入sysMenu的子菜单
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getPid, sysMenu.getId());
        List<SysMenu> childrens = this.list(wrapper);

        //如果没有子菜单,直接原样返回
        if(childrens.size() == 0){
            return sysMenu;
        }

        //如果有子菜单,递归查询子菜单的子菜单
        for (SysMenu children : childrens) {
            getChildren(children);
        }

        //将子菜单赋值给sysMenu
        sysMenu.setChildren(childrens);

        //返回sysMenu
        return sysMenu;

    }

    @Override
    public SysMenu getUseChildren(SysMenu sysMenu, List<SysRoleMenu> sysRoleMenus) {

        List<Integer> menuIds = sysRoleMenus.stream().map(item -> {
            return Integer.parseInt(item.getMenuId());
        }).collect(Collectors.toList());

        //查询出传入sysMenu的子菜单
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getPid, sysMenu.getId());
        wrapper.in(SysMenu::getId,menuIds);
        List<SysMenu> childrens = this.list(wrapper);

        //如果没有子菜单,直接原样返回
        if(childrens.size() == 0){
            return sysMenu;
        }

        //如果有子菜单,递归查询子菜单的子菜单
        for (SysMenu children : childrens) {
            getUseChildren(children,sysRoleMenus);
        }

        //将子菜单赋值给sysMenu
        sysMenu.setChildren(childrens);

        //返回sysMenu
        return sysMenu;

    }
}



